import os
import sys
import django
from django.apps import apps
from django.db import connection

# 获取项目根目录（脚本所在目录的上级目录）
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(project_root)

# 配置Django环境（使用你的settings路径）
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "luffy_crm.settings")
django.setup()

# 导入模型（严格匹配你的模型定义）
from rbac.models import Permission, Menu  # 确保rbac应用中存在这两个模型

# 权限数据（字段与模型完全对应，无多余参数）
PERMISSIONS_DATA = [
    # 权限管理相关
    {
        "title": "权限列表查看",
        "url": "/rbac/permission/list/",
        "name": "rbac:permission_list",
        "menu": None,  # 先设为None，后续关联实际菜单ID
        "pid": None
    },
    {
        "title": "权限添加",
        "url": "/rbac/permission/add/",
        "name": "rbac:permission_add",
        "menu": None,
        "pid": None  # 后续自动关联父权限
    },
    {
        "title": "权限编辑",
        "url": "/rbac/permission/edit/(?P<pk>\\d+)/",
        "name": "rbac:permission_edit",
        "menu": None,
        "pid": None
    },
    {
        "title": "权限删除",
        "url": "/rbac/permission/delete/(?P<pk>\\d+)/",
        "name": "rbac:permission_delete",
        "menu": None,
        "pid": None
    },
    # 角色管理相关
    {
        "title": "角色列表查看",
        "url": "/rbac/role/list/",
        "name": "rbac:role_list",
        "menu": None,
        "pid": None
    },
    {
        "title": "角色添加",
        "url": "/rbac/role/add/",
        "name": "rbac:role_add",
        "menu": None,
        "pid": None
    },
    {
        "title": "角色编辑",
        "url": "/rbac/role/edit/(?P<pk>\\d+)/",
        "name": "rbac:role_edit",
        "menu": None,
        "pid": None
    },
    {
        "title": "角色删除",
        "url": "/rbac/role/delete/(?P<pk>\\d+)/",
        "name": "rbac:role_delete",
        "menu": None,
        "pid": None
    },
    # 权限分配相关
    {
        "title": "权限分配",
        "url": "/rbac/permission/distribute/",
        "name": "rbac:permission_distribute",
        "menu": None,
        "pid": None
    },
    {
        "title": "批量操作权限",
        "url": "/rbac/permission/batch/",
        "name": "rbac:permission_batch",
        "menu": None,
        "pid": None
    }
]

def create_menus():
    """创建菜单数据（匹配你的Menu模型：title和icon字段）"""
    print("===== 开始创建菜单 =====")
    # 创建"权限管理"和"角色管理"菜单，设置图标（可根据实际需求修改图标名）
    menu_perm, _ = Menu.objects.get_or_create(
        title="权限管理",
        defaults={"icon": "fa-shield"}  # 示例图标（前端需支持）
    )
    menu_role, _ = Menu.objects.get_or_create(
        title="角色管理",
        defaults={"icon": "fa-users"}  # 示例图标
    )
    print(f"创建菜单：{menu_perm.title}（id={menu_perm.id}）、{menu_role.title}（id={menu_role.id}）")
    return menu_perm.id, menu_role.id

def set_permission_relations(menu_perm_id, menu_role_id):
    """设置权限的menu和pid关联（根据标题匹配）"""
    # 1. 关联menu
    perm_list = Permission.objects.all()
    for perm in perm_list:
        # "权限列表查看"和"权限分配"关联"权限管理"菜单
        if perm.title in ["权限列表查看", "权限分配"]:
            perm.menu_id = menu_perm_id
        # "角色列表查看"关联"角色管理"菜单
        elif perm.title == "角色列表查看":
            perm.menu_id = menu_role_id
        perm.save()

    # 2. 关联pid（父权限）
    # "权限添加/编辑/删除"的父权限是"权限列表查看"
    parent_perm = Permission.objects.get(title="权限列表查看")
    for title in ["权限添加", "权限编辑", "权限删除", "批量操作权限"]:
        child_perm = Permission.objects.get(title=title)
        child_perm.pid = parent_perm
        child_perm.save()

    # "角色添加/编辑/删除"的父权限是"角色列表查看"
    parent_role = Permission.objects.get(title="角色列表查看")
    for title in ["角色添加", "角色编辑", "角色删除"]:
        child_role = Permission.objects.get(title=title)
        child_role.pid = parent_role
        child_role.save()

    print("权限关联（menu和pid）设置完成")

def reset_all_migrations():
    """回滚所有自定义应用迁移，清理外键数据"""
    print("===== 清理外键数据 =====")
    # 清理house_user_roles表（解决外键错误）
    try:
        with connection.cursor() as cursor:
            cursor.execute("DELETE FROM house_user_roles;")
            print("已清空house_user_roles表")
    except Exception as e:
        print(f"清理失败：{e}")

    print("===== 回滚所有应用 =====")
    installed_apps = [app_config.name for app_config in apps.get_app_configs()]
    exclude_apps = [  # 排除Django内置应用
        'django.contrib.admin', 'django.contrib.auth',
        'django.contrib.contenttypes', 'django.contrib.sessions',
        'django.contrib.messages', 'django.contrib.staticfiles'
    ]
    for app in [a for a in installed_apps if a not in exclude_apps]:
        print(f"回滚应用：{app}")
        os.system(f"python {os.path.join(project_root, 'manage.py')} migrate {app} zero")
    print("===== 回滚完成 =====")

def apply_all_migrations():
    """重新应用所有迁移"""
    print("===== 应用迁移 =====")
    os.system(f"python {os.path.join(project_root, 'manage.py')} migrate")
    print("===== 迁移完成 =====")

def create_permissions():
    """创建权限数据"""
    print("===== 创建权限 =====")
    Permission.objects.all().delete()  # 清空旧数据
    # 批量创建权限（先不设置menu和pid，后续单独处理）
    permissions = [Permission(**data) for data in PERMISSIONS_DATA]
    Permission.objects.bulk_create(permissions)
    print(f"创建了{len(permissions)}条权限")

def full_reset():
    """完整流程：回滚->迁移->创建菜单->创建权限->设置关联"""
    try:
        reset_all_migrations()
        apply_all_migrations()
        menu_perm_id, menu_role_id = create_menus()
        create_permissions()
        set_permission_relations(menu_perm_id, menu_role_id)
        print("\n===== 所有操作完成！=====")
    except Exception as e:
        print(f"\n出错：{str(e)}")

if __name__ == "__main__":
    confirm = input("警告：将回滚所有数据并重建！继续？(y/n): ")
    if confirm.lower() == 'y':
        full_reset()
    else:
        #  python scripts/permission_reset.py 执行脚本
        print("操作取消")
